package com.carassistant.beta.phone;

import java.util.ArrayList;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.CarAssistantActivity;
import com.carassistant.beta.common.CarAssistantApp;
import com.carassistant.beta.phone.adapter.KeypadContactAdapter;
import com.carassistant.beta.phone.entity.ContactInfo;

public class PhoneKeypadActivity extends CarAssistantActivity implements OnLongClickListener,OnItemClickListener{
	private Button phone_view,delete,dialNum1,dialNum2,dialNum3,dialNum4,dialNum5,dialNum6,dialNum7,dialNum8,dialNum9,dialx,dialNum0,dialj;
	private StringBuffer inputNumBuffer = new StringBuffer();

	private ListView contactList;
	private ArrayList<ContactInfo> allContactList;
	private KeypadContactAdapter adapter;
	
	private AsyncQueryHandler asyncQuery;  
	public static final int TOKEN_ONCREATE = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_keypad);
		
		asyncQuery = new MyAsyncQueryHandler(getContentResolver()); 
		getContacts(TOKEN_ONCREATE); 
		
		init();
	}
	
	/**
     * 异步查询所有联系人
     * @param int
     * */
    private void getContacts(int token){
    	String[] projection = {
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER,
				ContactsContract.CommonDataKinds.Phone.TYPE, "sort_key" };
		asyncQuery.startQuery(token, null,
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
				null, null, "sort_key COLLATE LOCALIZED asc");
    }
	
	private void init(){
		phone_view = (Button) findViewById(R.id.phone_view);
		delete = (Button) findViewById(R.id.delete);
		dialNum1 = (Button) findViewById(R.id.dialNum1);
		dialNum2 = (Button) findViewById(R.id.dialNum2);
		dialNum3 = (Button) findViewById(R.id.dialNum3);
		dialNum4 = (Button) findViewById(R.id.dialNum4);
		dialNum5 = (Button) findViewById(R.id.dialNum5);
		dialNum6 = (Button) findViewById(R.id.dialNum6);
		dialNum7 = (Button) findViewById(R.id.dialNum7);
		dialNum8 = (Button) findViewById(R.id.dialNum8);
		dialNum9 = (Button) findViewById(R.id.dialNum9);
		dialx = (Button) findViewById(R.id.dialx);
		dialNum0 = (Button) findViewById(R.id.dialNum0);
		dialj = (Button) findViewById(R.id.dialj);
		
		phone_view.setOnClickListener(this);
		delete.setOnClickListener(this);
		dialNum1.setOnClickListener(this);
		dialNum2.setOnClickListener(this);
		dialNum3.setOnClickListener(this);
		dialNum4.setOnClickListener(this);
		dialNum5.setOnClickListener(this);
		dialNum6.setOnClickListener(this);
		dialNum7.setOnClickListener(this);
		dialNum8.setOnClickListener(this);
		dialNum9.setOnClickListener(this);
		dialx.setOnClickListener(this);
		dialNum0.setOnClickListener(this);
		dialj.setOnClickListener(this);
		
		delete.setOnLongClickListener(this);
		dialNum0.setOnLongClickListener(this);
		
		contactList = (ListView) findViewById(R.id.contactList);
		contactList.setOnItemClickListener(this);
		
		phone_view.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(allContactList!=null){
					if(null == adapter){
						adapter = new KeypadContactAdapter(PhoneKeypadActivity.this);
						adapter.assignment(allContactList);
						contactList.setAdapter(adapter);
						contactList.setTextFilterEnabled(true);
					}else{
						adapter.getFilter().filter(s);
					}
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		
		switch (v.getId()) {
		case R.id.phone_view:
			dailNumber(inputNumBuffer.toString());
			break;
		case R.id.delete:
			int count = inputNumBuffer.length();
			if (count == 0) { 
				break;
			} 
			inputNumBuffer.deleteCharAt(inputNumBuffer.length()-1);
			phone_view.setText(inputNumBuffer.toString());
			break;
		default:
			String number = (String) v.getTag();
			if (number != null) {
				addNumber(number);
			}
			break;
		}
	}
	
	@Override
	public boolean onLongClick(View v) {
		switch (v.getId()) {
		case R.id.delete:
			if (inputNumBuffer.length() != 0) {
				inputNumBuffer.delete(0, inputNumBuffer.length());
			} 
			phone_view.setText(""); 
			break;
		case R.id.dialNum0:
			addNumber("+");
			break;

		default:
			break;
		}
		return true;
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		TextView numberTv = (TextView) arg1.findViewById(R.id.numAddr);
		dailNumber(numberTv.getText().toString());
	}
	
	private void addNumber(String number){
		if(inputNumBuffer.length()<15){
			inputNumBuffer.append(number);
			phone_view.setText(inputNumBuffer.toString());
		}
	}
	
	private void dailNumber(String number){
		if (number != null && !"".equals(number)) {
			Uri callUri = Uri.parse("tel:" + number);
			startActivity(new Intent(Intent.ACTION_CALL, callUri));
		} 
	}
	
	//查询联系人
    private class MyAsyncQueryHandler extends AsyncQueryHandler {  
        public MyAsyncQueryHandler(ContentResolver cr) {  
            super(cr);  
  
        }  
  
        @Override  
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {  
            if (cursor != null && cursor.getCount() > 0) {  
            	allContactList = new ArrayList<ContactInfo>();
            	
                while (cursor.moveToNext()) {
                	Long id = cursor.getLong(0);  
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                
                    ContactInfo contactInfo = new ContactInfo();
					contactInfo.setId(id);
					contactInfo.setPhoneNum(number);
					contactInfo.setName(name);
					if (contactInfo.getName() == null) {
						contactInfo.setName(contactInfo.getPhoneNum());
					}
					contactInfo.setFormattedNumber(getNameNum(contactInfo.getName() + ""));
					try {
						contactInfo.setPinyin(CarAssistantApp.getPinYin(contactInfo.getName() + ""));
					} catch (BadHanyuPinyinOutputFormatCombination e) {
						e.printStackTrace();
					}
					allContactList.add(contactInfo);
                }  
             
                cursor.close();
            }  
        }  
  
    }
    
    private String getNameNum(String name) {
		try {
			if (name != null && name.length() != 0) {
				int len = name.length();
				char[] nums = new char[len];
				for (int i = 0; i < len; i++) {
					String tmp = name.substring(i);
					nums[i] = getOneNumFromAlpha(CarAssistantApp.getPinYin(tmp).toLowerCase().charAt(0));
				}
				return new String(nums);
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return null;
	}
    
    private char getOneNumFromAlpha(char firstAlpha) {
		switch (firstAlpha) {
		case 'a':
		case 'b':
		case 'c':
			return '2';
		case 'd':
		case 'e':
		case 'f':
			return '3';
		case 'g':
		case 'h':
		case 'i':
			return '4';
		case 'j':
		case 'k':
		case 'l':
			return '5';
		case 'm':
		case 'n':
		case 'o':
			return '6';
		case 'p':
		case 'q':
		case 'r':
		case 's':
			return '7';
		case 't':
		case 'u':
		case 'v':
			return '8';
		case 'w':
		case 'x':
		case 'y':
		case 'z':
			return '9';
		default:
			return '0';
		}
	}
}
